package logic

import (
	"context"
	"encoding/json"

	"googee/common/errorx"
	"googee/common/tool"
	"googee/service/sms/rpc/types/sms"
	"googee/service/user/api/internal/svc"
	"googee/service/user/api/internal/types"
	"googee/service/user/rpc/user"

	"github.com/zeromicro/go-zero/core/logx"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

type BindphoneLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewBindphoneLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BindphoneLogic {
	return &BindphoneLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *BindphoneLogic) Bindphone(req *types.BindPhoneReq) (resp *types.BaseReply, err error) {
	logx.Infof("userId: %v", l.ctx.Value("userId"))
	resp = &types.BaseReply{}
	resp.Msg = "绑定成功"

	phone := req.Phone
	if !tool.VerifyMobileFormat(phone) {
		return nil, errorx.NewCodeErrorNoMsg(errorx.USER_ERROR + 4)
	}

	id, err := l.ctx.Value("userId").(json.Number).Int64()
	if err != nil {
		return nil, err
	}

	code := req.Code
	if code == "" {
		return nil, errorx.NewCodeErrorNoMsg(errorx.USER_ERROR + 2)
	}

	//查看我自己是否已经绑定了手机号
	u, _ := l.svcCtx.User.GetUser(l.ctx, &user.IdRequest{Id: id})
	if u.GetPhone() != "" {
		return nil, errorx.NewCodeErrorNoMsg(errorx.USER_ERROR + 11)
	}

	//检查验证码是否失效
	result, err := l.svcCtx.Sms.VerifyCode(l.ctx, &sms.VerifyRequest{Phone: phone, Id: id, Code: req.Code})
	if err != nil {
		st, ok := status.FromError(err)
		if ok {
			if st.Code() == codes.InvalidArgument {
				return nil, errorx.NewCodeErrorNoMsg(errorx.USER_ERROR + 2)
			} else if st.Code() == codes.NotFound {
				return nil, errorx.NewCodeErrorNoMsg(errorx.USER_ERROR + 10)
			} else {
				return nil, errorx.NewCodeError(errorx.INTERNAL_ERROR, "系统内部未知错误")
			}
		} else {
			return nil, errorx.NewCodeError(errorx.INTERNAL_ERROR, "系统内部未知错误")
		}
	}

	if result.Code != 0 {
		return nil, errorx.NewCodeErrorNoMsg(errorx.USER_ERROR + 10)
	}

	_, err = l.svcCtx.User.BindPhone(l.ctx, &user.BindPhoneRequest{Id: id, Phone: req.Phone})
	if err != nil {
		st, ok := status.FromError(err)
		if ok {
			if st.Code() == codes.AlreadyExists {
				return nil, errorx.NewCodeErrorNoMsg(errorx.USER_ERROR + 5)
			} else {
				return nil, errorx.NewCodeError(errorx.INTERNAL_ERROR, "系统内部未知错误")
			}
		} else {
			return nil, errorx.NewCodeError(errorx.INTERNAL_ERROR, "系统内部未知错误")
		}
	}

	return
}
